<template>
  <div>
    <!--面包导航-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--查询条件-->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" clearable v-model="queryInfo.query" @clear="getUsersList">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--用户列表-->
      <el-table :data="usersList" border stripe style="width: 100%; margin-top:10px">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
        <el-table-column prop="mg_state" label="状态" width="180">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <el-tooltip content="修改" placement="top" :enterable="false">
              <el-button
                type="primary"
                @click="showEditDialog(scope.row.id)"
                icon="el-icon-edit"
                size="mini"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" :enterable="false">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!--弹出对话框-->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="closeDialog">
      <span>
        <el-form ref="userFromRef" :model="userForm" :rules="userFormRules" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input :disabled="!editStatus" v-model="userForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" v-if="editStatus">
            <el-input type="password" v-model="userForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="userForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUsersListService,
  changeUserStatus,
  saveUserService,
  getUserByIdService,
  deleteUserByIdService
} from '../../network/users'

import userRules from './userRules'

export default {
  data() {
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      editStatus: true,
      usersList: [],
      total: 0,
      dialogVisible: false,
      userForm: {
        id: 0,
        username: '',
        password: '',
        mobile: '',
        email: ''
      },
      userFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: userRules.FormValidate.Form().validatePsdReg }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: userRules.FormValidate.Form().validatePhone }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: userRules.FormValidate.Form().validateEmail }
        ]
      }
    }
  },
  created() {
    this.getUsersList()
  },
  methods: {
    async getUsersList() {
      const { data: res } = await getUsersListService(this.queryInfo)
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.usersList = res.data.users
      this.total = res.data.total
    },
    // pageSize改变事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUsersList()
    },
    // pageIndex改变事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUsersList()
    },
    // 监听用户状态改变
    async userStateChange(userInfo) {
      const params = `/${userInfo.id}/state/${userInfo.mg_state}`
      const { data: res } = await changeUserStatus(params)
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新状态成功！')
    },
    // 关闭弹出框时，重置表单
    closeDialog() {
      this.$refs.userFromRef.resetFields()
      this.editStatus = true

      this.userForm.id = 0
      this.userForm.username = ''
      this.userForm.password = ''
      this.userForm.mobile = ''
      this.userForm.email = ''
    },
    // 点击添加新用户
    addUser() {
      this.$refs.userFromRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await saveUserService(this.userForm)

        // 新增
        if (this.userForm.id === 0) {
          if (res.meta.status !== 201) return this.$message.error('添加失败')
          this.$message.success('添加成功')
        } else {
          // 修改
          if (res.meta.status !== 200) return this.$message.error('修改失败')
          this.$message.success('修改成功')
        }

        // 关闭对话框
        this.dialogVisible = false

        // 重新获取用户数据
        this.getUsersList()
      })
    },
    // 修改用户对话框
    async showEditDialog(id) {
      const { data: res } = await getUserByIdService(id)

      if (res.meta.status !== 200) return this.$message.error('获取数据失败')

      this.userForm = res.data
      this.dialogVisible = true
      this.editStatus = false
    },
    async removeUser(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      if (confirmResult !== 'confirm') {
        return this.$message.warning('用户取消了删除')
      }

      const { data: res } = await deleteUserByIdService(id)

      if (res.meta.status !== 200) return this.$message.error('删除用户失败')

      this.$message.success('删除用户成功')

      this.getUsersList()
    }
  }
}
</script>

<style lang="less" scoped>
</style>
